<template>
  <section class="news-main">
    <el-collapse-transition>
      <section v-show="searchshow" class="main-search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input
          v-model.trim="listQuery.mainTitle"
          placeholder="输入新闻标题搜索"
          class="search-input"
          @keyup.enter.native="handleFilter"
        />
        <section class="search-btn">
          <el-button
            class="filter-item"
            type="primary"
            @click="handleFilter"
          >搜索</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
          <span class="search-more" @click="searchshow = !searchshow">
            更多筛选条件
            <i class="el-icon-arrow-down" />
          </span>
        </section>
      </section>
    </el-collapse-transition>
    <el-collapse-transition>
      <section v-show="!searchshow" class="main-search separate">
        <section class="search-inner">
          <el-row>
            <el-col :span="12">
              <section class="search-inner-item">
                <div class="item-label">新闻标题</div>
                <el-input
                  v-model.trim="search.mainTitle"
                  style="width: 90%"
                  class="filter-item"
                  placeholder="请输入新闻标题搜索"
                />
              </section>
            </el-col>
            <el-col :span="12">
              <section class="search-inner-item">
                <div class="item-label">简介</div>
                <el-input
                  v-model.trim="search.briefIntroduction"
                  style="width: 90%"
                  class="filter-item"
                  placeholder="请输入新闻简介搜索"
                />
              </section>
            </el-col>
            <el-col :span="12">
              <section class="search-inner-item">
                <div class="item-label">来源</div>
                <el-input
                  v-model.trim="search.source"
                  style="width: 90%"
                  class="filter-item"
                  placeholder="请输入新闻来源搜索"
                />
              </section>
            </el-col>
          </el-row>
        </section>
        <section class="search-btn">
          <el-button type="primary" @click="handleFilter">搜索</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
          <span class="search-more" @click="searchshow = !searchshow">
            精简筛选条件
            <i class="el-icon-arrow-up" />
          </span>
        </section>
      </section>
    </el-collapse-transition>

    <section class="main-buttons">
      <section class="main-buttons-title">
        <span>新闻列表</span>
      </section>
      <section class="main-buttons-btns" />
      <el-button
        style="margin-left: 10px"
        @click="handleCreate"
      >新建</el-button>
      <el-button
        style="margin-left: 10px"
        @click="handleSelectPlatform"
      >选取SaaS平台新闻
      </el-button>
      <el-button
        style="margin-left: 10px"
        @click="handleMultiSet"
      >批量设置</el-button>
    </section>
    <div class="classify-tab">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane
          v-for="item in classifyOptions"
          :key="item.id"
          :label="item.classifyName"
          :name="item.id"
        />
      </el-tabs>
    </div>
    <section class="main-table">
      <v-table
        :list="list"
        tag="news"
        :list-loading="listLoading"
        :filter-column="filtercolumn"
        :selection="false"
      >
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          min-width="120"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="handleView(scope.row)"
            >预览</el-button>
            <el-button
              v-if="
                scope.row.status !== 'GIPSTSTUS01' && !scope.row.relevanceId
              "
              type="text"
              size="mini"
              @click="handleUpdate(scope.row)"
            >编辑</el-button>
            <el-button
              v-if="scope.row.isForce !== 'SF01'"
              type="text"
              size="mini"
              @click="handlePublish(scope.row)"
            >{{
              scope.row.status === 'GIPSTSTUS01' ? '取消发布' : '发布'
            }}</el-button>
            <el-button type="text" size="mini" @click="handleTop(scope.row)">{{
              scope.row.isTop == '1' ? '取消置顶' : '置顶'
            }}</el-button>
            <el-button
              v-if="!scope.row.relevanceId"
              type="text"
              size="mini"
              @click="handleSet(scope.row)"
            >设置</el-button>
            <el-button
              v-if="scope.row.isForce !== 'SF01'"
              type="text"
              size="mini"
              @click="deleteNews(scope.row.id)"
            >删除</el-button>
            <el-button
              type="text"
              size="mini"
              @click="handleComment(scope.row.id)"
            >查看评论</el-button>
            <el-button
              type="text"
              size="mini"
              @click="handleAddress(scope.row.id)"
            >查看地址</el-button>
            <el-button
              v-if="scope.row.isForce === 'SF01'"
              type="text"
              size="mini"
              @click="handleSort(scope.row)"
            >修改排序</el-button>
          </template>
        </el-table-column>
      </v-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
      <news-set
        v-if="newsSetStatus"
        :id="newsItem.id"
        :obj="newsItem"
        :type="setType"
        @closeSet=";(newsSetStatus = false), getList()"
      />
      <preview
        v-if="newsPreviewStatus"
        :id="newsItem.id"
        @closeSet="newsPreviewStatus = false"
      />
      <el-dialog
        v-el-drag-dialog
        title="修改排序"
        width="30%"
        :visible.sync="sortDialog"
        @close="cancelDialog"
      >
        <el-input
          v-model="form.sort"
          placeholder="请输入排序值"
          type="number"
        />
        <span slot="footer" class="dialog-footer">
          <el-button
            style="padding: 8px 30px"
            @click="cancelDialog"
          >取 消</el-button>
          <el-button
            style="padding: 8px 30px"
            type="primary"
            @click="handelUpdateSort"
          >确 定</el-button>
        </span>
      </el-dialog>
    </section>
  </section>
</template>
<script>
import Pagination from '@/components/Pagination'
import VTable from '@/components/Table'
import {
  getClassifyTree,
  queryPage,
  del,
  updateState,
  updateIsTop,
  update
} from '../api'
import permission from '@/directive/permission/index.js'
import NewsSet from '../components/NewsSet'
import Preview from '../components/Preview'
import elDragDialog from '@/directive/el-drag-dialog'
export default {
  name: 'NewsMain',
  components: { Pagination, VTable, NewsSet, Preview },
  directives: { permission, elDragDialog },
  data() {
    return {
      listQuery: {
        page: 1,
        limit: 10,
        mainTitle: ''
      },
      searchshow: true,
      search: {
        mainTitle: '',
        source: '',
        briefIntroduction: ''
      },
      classifyOptions: [],
      activeTab: '',
      list: [],
      total: 0,
      listLoading: false,
      newsSetStatus: false,
      newsPreviewStatus: false,
      newsItem: {},
      setType: 'single',
      link: '/newsDetail?bt=xw&i=',
      form: {
        id: '',
        sort: ''
      },
      sortDialog: false
    }
  },
  created() {
    this.getClassifyOption()
  },
  methods: {
    handleSelectPlatform() {
      this.$router.push({
        path: '/information/news/SelectCourse4platform',
        query: {}
      })
    },
    /**
		 * 获取分类
		 */
    getClassifyOption() {
      return new Promise((resolve, reject) => {
        getClassifyTree({ classifyType: 'XWFL_XWGL' })
          .then(({ data }) => {
            this.classifyOptions = data.data || []
            this.activeTab = this.$route.query.c || data.data[0].id
            this.getList()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    /**
		 * 新建
		 */
    handleCreate() {
      this.$router.push({
        path: this.$filterPath('manage'),
        query: { type: 'c', c: this.activeTab === '0' ? '' : this.activeTab }
      })
    },
    /**
		 * 批量设置
		 */
    handleMultiSet() {
      this.setType = 'multi'
      this.newsSetStatus = true
    },
    /**
		 * 预览
		 */
    handleView(row) {
      this.newsItem = Object.assign({}, row)
      this.newsPreviewStatus = true
    },
    /**
		 * 查看评论
		 */
    handleComment(id) {
      this.$router.push({
        path: this.$filterPath('comment'),
        query: { i: id, c: this.activeTab === '0' ? '' : this.activeTab }
      })
    },
    /**
		 * 查看前端地址
		 */
    handleAddress(id) {
      this.$confirm(
        `链接地址为：${this.link}${id}<span style="color:red">注意：该链接只对已发布数据有效</span>`,
        '提示',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '复制链接',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          const input = document.createElement('input')
          input.setAttribute('readonly', 'readonly')
          input.setAttribute('value', this.link + id)
          document.body.appendChild(input)
          input.select()
          if (document.execCommand('copy')) {
            document.execCommand('copy')
            this.$message({
              title: '成功',
              message: '复制成功！',
              type: 'success',
              duration: 1500
            })
          }
          document.body.removeChild(input)
        })
        .catch(() => {})
    },
    /**
		 * 编辑
		 */
    handleUpdate(row) {
      this.$router.push({
        path: this.$filterPath('manage'),
        query: { i: row.id, type: 'u' }
      })
    },
    /**
		 * 发布/取消发布
		 */
    handlePublish(row) {
      this.$confirm(
        row.status === 'GIPSTSTUS01' ? '确认取消发布？' : '确认发布？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          updateState({
            id: row.id,
            status:
							row.status === 'GIPSTSTUS01' ? 'GIPSTSTUS02' : 'GIPSTSTUS01'
          }).then((res) => {
            if (res.data.code === '200') {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.getList()
            }
          })
        })
        .catch(() => {})
    },
    /**
		 * 置顶/取消置顶
		 */
    handleTop(row) {
      this.$confirm(
        row.isTop === '1' ? '确认取消置顶？' : '确认置顶？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          updateIsTop({
            id: row.id,
            isTop: row.isTop === '1' ? '2' : '1'
          }).then((res) => {
            if (res.data.code === '200') {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.getList()
            }
          })
        })
        .catch(() => {})
    },
    /**
		 * 设置
		 */
    handleSet(row) {
      this.setType = 'single'
      this.newsItem = Object.assign({}, row)
      this.newsSetStatus = true
    },
    /**
		 * 选项卡切换
		 */
    handleTabClick(tab, event) {
      this.listQuery.page = 1
      this.getList()
    },
    deleteNews(ids) {
      this.$confirm('此操作将永久删除该新闻, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          return new Promise((resolve, reject) => {
            del({ id: ids })
              .then(() => {
                loading.close()
                this.$message({
                  title: '成功',
                  message: '删除成功',
                  type: 'success',
                  duration: 2000
                })
                this.getList()
              })
              .catch((error) => {
                loading.close()
                reject(error)
              })
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    filtercolumn(scope, item) {
      return scope.row[item]
    },

    handleReset() {
      this.listQuery.page = 1
      this.listQuery.mainTitle = ''
      for (const i in this.search) {
        if (this.search['' + i + ''] instanceof Array) {
          this.search['' + i + ''] = []
        } else {
          this.search['' + i + ''] = ''
        }
      }
      this.getList()
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    getList(obj) {
      this.listLoading = true
      var query = {
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit,
        newsType: this.activeTab
      }
      if (this.searchshow) {
        query['mainTitle'] = this.listQuery.mainTitle
      } else {
        query['mainTitle'] = this.search.mainTitle
        query['source'] = this.search.source
        query['briefIntroduction'] = this.search.briefIntroduction
      }
      return new Promise((resolve, reject) => {
        queryPage(query)
          .then((response) => {
            this.list = response.data.data.rows
            this.total = response.data.data.total
            this.listLoading = false
          })
          .catch((error) => {
            reject(error)
            this.listLoading = false
          })
      })
    },

    // 修改排序
    handelUpdateSort() {
      if (this.form.sort === '') {
        this.$message({
          message: '请输入排序值',
          type: 'warning'
        })
        return
      }
      const obj = Object.assign({}, this.form)
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      update(obj)
        .then((res) => {
          if (res.data.code === '200') {
            loading.close()
            this.sortDialog = false
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.getList()
          } else {
            loading.close()
            this.$message({
              message: '修改失败',
              type: 'error'
            })
          }
        })
        .catch(() => {
          loading.close()
        })
    },

    // 强制下发数组修改排序
    handleSort(row) {
      console.log(row, '482')
      this.form.id = row.id
      this.sortDialog = true
    },

    // 取消修改排序
    cancelDialog() {
      this.sortDialog = false
      for (const k in this.form) {
        this.form[k] = ''
      }
    }
  }
}
</script>
<style lang="scss">
.news-main {
	padding: 10px;
	.main-search {
		background-color: #fff;
		padding: 0 10px;
		.svg-container {
			padding: 0 5px 0 10px;
			color: #bfced6;
			vertical-align: middle;
			display: inline-block;
		}
		.search-input {
			width: 60%;
			position: relative;
			&:after {
				content: '';
				position: absolute;
				left: -25px;
				right: 0;
				bottom: 8px;
				height: 1px;
				background: rgba(226, 227, 232, 1);
			}
			input {
				outline: none;
				background: transparent;
				border: none;
				outline: medium;
				padding: 0;
				&:focus {
					outline: none;
					background-color: transparent;
				}
			}
		}
		.search-btn {
			display: inline-block;
			float: right;
			.el-button.is-round {
				padding: 10px 30px;
				margin-right: 34px;
			}
			.search-more {
				font-size: 14px;
				font-weight: 500;
				@include font-color($mainColor);
				cursor: pointer;
				margin-left: 10px;
			}
		}

		&.merge {
			height: 50px;
			line-height: 50px;
		}

		&.separate {
			.search-inner {
				padding-top: 10px;
				.search-inner-item {
					.item-label {
						height: 30px;
						line-height: 30px;
						font-size: 14px;
						color: #a6a6a6;
						font-weight: 400;
					}
					.el-input {
						position: relative;
						&.el-date-editor input {
							padding-left: 30px;
						}
						.el-input__inner {
							border: none;
							padding: 0;
						}
						&:after {
							content: '';
							height: 1px;
							background-color: #e2e3e8;
							position: absolute;
							left: 0;
							right: 0;
							bottom: 0;
						}
					}
				}
			}
			.search-btn {
				text-align: center;
				display: block;
				float: none;
				height: 56px;
				line-height: 56px;
			}
		}
	}
	.classify-tab {
		width: 100%;
		margin: 10px 0;
		padding: 0 10px;
		background-color: #fff;
		display: flex;
		border-radius: 4px;
		.el-tabs {
			width: 100%;
		}
		.el-tabs__nav-wrap::after {
			display: none;
		}
		.el-tabs__header {
			margin: 0;
		}
	}
	.main-buttons {
		display: flex;
		line-height: 36px;
		margin-top: 10px;
		.main-buttons-title {
			flex: 1;
			height: 36px;
			line-height: 36px;
			font-size: 16px;
			font-weight: bold;
			color: rgba(51, 51, 51, 1);
		}
	}
}
</style>
